package gw.com.android.presenter.http;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.interfaces.ReqCallBack;

/**
 * 交易策略请求的接口
 *
 * @author jett
 * @since 2017-11-28.
 */
public class StrategyRequest {

    private int currentPage;
    private int pageSize = 10;
    private int totalSize = -1;

    private DateFormat sourceFormat;
    private boolean overSevenDayLimit = false; // 客户端需限制只能获取7天内的交易策略。

    public List<ArticleData> fetchLocal() {
        String str = CacheUtils.readFile("strategy_news.data");
        return parse(str, false);
    }

    /**
     * 首页获取新一条的交易策略
     */
    public void getLast(final ReqCallBack<StrategyRequest.ArticleData> callBack) {
        sendRequest(1, 1, new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                StrategyRequest.ArticleData content = null;
                List<ArticleData> list = parse(result, false);
                if (list != null && !list.isEmpty()) {
                    content = list.get(0);
                }
                if (callBack != null) {
                    callBack.onReqSuccess(content);
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                if (callBack != null) {
                    callBack.onReqFailed(e == null ? null : e.getMessage());
                }
            }
        });
    }

    /**
     * 分页获取交易策略
     */
    public void getList(final ReqCallBack<List<ArticleData>> callBack) {
        currentPage = 1;
        overSevenDayLimit = false;
        sendRequest(currentPage, pageSize, new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                List<ArticleData> list = parse(result, true);
                if (callBack != null) {
                    callBack.onReqSuccess(list);
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                if (callBack != null) {
                    callBack.onReqFailed(e == null ? null : e.getMessage());
                }
            }
        });
    }

    public boolean hasNextPage() {
        if (overSevenDayLimit) {
            return false;
        }
        if (totalSize > 0) {
            return (totalSize - 1) / pageSize > currentPage - 1;
        }
        return false;
    }

    public void nextPage(final ReqCallBack<List<ArticleData>> callBack) {
        sendRequest(++currentPage, pageSize, new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                List<ArticleData> list = parse(result, false);
                if (callBack != null) {
                    callBack.onReqSuccess(list);
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                currentPage--;
                if (callBack != null) {
                    callBack.onReqFailed(e == null ? null : e.getMessage());
                }
            }
        });
    }

    private List<ArticleData> parse(String result, boolean cache) {
        if (TextUtils.isEmpty(result)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(result);
            totalSize = jsonObject.optInt("totalRecords", -1);
            JSONArray dataArr = jsonObject.optJSONArray("data");
            if (dataArr == null || dataArr.length() <= 0) {
                return null;
            }
            List<ArticleData> list = new ArrayList<>();
            for (int i = 0; i < dataArr.length(); i++) {
                JSONObject dataJson = dataArr.optJSONObject(i);
                if (dataJson == null) {
                    continue;
                }
                JSONArray detailList = dataJson.optJSONArray("detailList");
                if (detailList == null || detailList.length() <= 0) {
                    continue;
                }
                JSONObject detail = detailList.optJSONObject(0);
                if (detail == null) {
                    continue;
                }
                JSONObject authorInfo = detail.optJSONObject("authorInfo");
                if (authorInfo == null) {
                    continue;
                }
                ArticleData data = new ArticleData();
                data.authorName = authorInfo.optString("name");
                data.iconUrl = authorInfo.optString("avatar");
                data.content = detail.optString("content");
                data.title = detail.optString("title");
                data.publishStartDate = dataJson.optString("publishStartDate");
                data.id = dataJson.optString("_id");
                data.date = formatCreateDate(data.publishStartDate);
                if (overSevenDayLimit(data.date)) {
                    overSevenDayLimit = true;
                    break;
                }
                list.add(data);
            }
            if (cache) {
                CacheUtils.writeFile("strategy_news.data", result);
            }
            return list;
        } catch (JSONException e) {
            Logger.e(e);
        }
        return null;
    }

    private Calendar sevenDayAgo;

    private boolean overSevenDayLimit(Date date) {
        if (sevenDayAgo == null) {
            sevenDayAgo = Calendar.getInstance();
            int year = sevenDayAgo.get(Calendar.YEAR);
            int month = sevenDayAgo.get(Calendar.MONTH);
            int day = sevenDayAgo.get(Calendar.DAY_OF_MONTH);
            sevenDayAgo.set(year, month, day - 7, 0, 0, 0);
        }
        return sevenDayAgo.getTimeInMillis() > date.getTime();
    }

    private Date formatCreateDate(String createDate) {
        if (!TextUtils.isEmpty(createDate)) {
            try {
                if (sourceFormat == null) {
                    sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
                    sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                }
                return sourceFormat.parse(createDate);
            } catch (ParseException ignore) {
            }
        }
        return new Date();
    }

    private void sendRequest(int pageNo, int pageSize, Https.ResponseCallback<?> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/article/getArticleList";
        JSONObject orderByJson = new JSONObject();
        try {
            // 排序字段，根据createdate 倒序
            orderByJson.put("publishStartDate", "desc");
            //orderByJson.put("publishStartDate", "desc");
        } catch (JSONException ignore) {
        }
        new Https().url(url)
                .addParam("code", "class_note")
                .addParam("platform", "hxstudio_1")
                .addParam("pageNo", String.valueOf(pageNo))
                .addParam("pageSize", String.valueOf(pageSize))
                .addParam("isAll", "1")
                .addParam("lang", "zh")
                .addParam("hasContent", "1")
                .addParam("orderByJsonStr", orderByJson.toString())
                .addParam("systemCategory", "hx")
                .addParam("companyId", "hx")
                .get(callback);
    }

    public class ArticleData {
        public String id;
        private String publishStartDate;
        public String iconUrl;
        public String authorName;
        public String content;
        public String title;
        public Date date;
    }

}
